//
//  DDSearchViewController.m
//  ialone
//
//  Created by 陆翀 on 16/1/13.
//  Copyright © 2016年 JasperSong. All rights reserved.
//

#import "DDSearchViewController.h"
#import "DDSoundModel.h"
#import "DDSoundTableViewCell.h"
#import "DDSoundDetailsViewController.h"
@interface DDSearchViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchResultsUpdating>
@property (strong,nonatomic) NSArray  *dataList;

@property (strong,nonatomic) NSMutableArray  *searchList;

@property (strong,nonatomic) UITableView *tableview;

@property (nonatomic,strong) UISearchController *searchController;

@property (nonatomic,strong) UIView *viewshow;
@end

@implementation DDSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
     _searchList = [NSMutableArray array];
    self.titleLabel.text = _str1;
    self.titleLabel.font = [UIFont systemFontOfSize:28];
    
    [self.leftButton addTarget:self action:@selector(leftButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.leftButton setImage:[UIImage imageNamed:@"item_cancel@2x"] forState:(UIControlStateNormal)];
    
    self.dataList=[NSMutableArray arrayWithCapacity:100];
    
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight-64) style:UITableViewStylePlain];
    self.tableview.dataSource =self;
    self.tableview.delegate = self;
    self.tableview.rowHeight = 120;
    self.tableview.scrollEnabled = NO;
    [self.view addSubview:self.tableview];
    
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    _searchController.searchResultsUpdater = self;
    //设置开始搜索时背景显示与否
    _searchController.dimsBackgroundDuringPresentation = YES;
    //搜索时 设置显示导航栏与否
    _searchController.hidesNavigationBarDuringPresentation = YES;
    //搜索时背景变模糊
    _searchController.obscuresBackgroundDuringPresentation = NO;
    
    
    
    
    [self.searchController.searchBar sizeToFit];
    
    _searchController.searchBar.frame = CGRectMake(0, 0, kScreenWidth, 44);
    
    self.tableview.tableHeaderView = _searchController.searchBar;
    
    _viewshow = [[UIView alloc]initWithFrame:CGRectMake(0, 64+44, kScreenWidth, kScreenHeight-44-64)];
    _viewshow.backgroundColor = [UIColor whiteColor];
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, kScreenHeight/5, kScreenWidth, 5*kLMarge)];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"热门搜索";
    [_viewshow addSubview:label];
    NSArray *array = @[@"贾樟柯",@"情人",@"艺术",@"阿乙",@"文学",@"社会"];
    for(int i = 0; i < 6; i++)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(kScreenWidth/5*2, label.bottom  +i*5*kLMarge, kScreenWidth/5, 5*kLMarge) ;
        [button setTitle:array[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:20];
        [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
        [_viewshow addSubview:button];
        
    }
    
    [self.view addSubview:_viewshow];
    
}
-(void)setUpData
{
    NSURL *url = [NSURL URLWithString:@"http://static.owspace.com/?index.php?m=Home&c=Api&a=search&page_id=0&create_time=0" ];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
    NSString *str = @"B709CBC5-0E2F-4C89-9E24-6AFBBA86C58C=device_id&iOS_version%3D1.0.0=version&key=%E8%B4%BE%E6%A8%9F%E6%9F%AF&p=1";
    str = [str stringByReplacingOccurrencesOfString:@"%E8%B4%BE%E6%A8%9F%E6%9F%AF" withString:_searchController.searchBar.text];
//    B709CBC5-0E2F-4C89-9E24-6AFBBA86C58C=device_id&iOS_version%3D1.0.0=version&key=%E8%B4%BE%E6%A8%9F%E6%9F%AF&p=1
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    [request setHTTPMethod:@"post"];
    [request setHTTPBody:data];
    
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        _dataList = dic[@"datas"][@"lists"];
        
        if (self.searchList!= nil) {
            [self.searchList removeAllObjects];
        }
       
        for (NSDictionary *one in _dataList) {
            DDSoundModel *model = [[DDSoundModel alloc]init];
            [model setValuesForKeysWithDictionary:one];
            [_searchList addObject:model];
        }
        
        [_tableview reloadData];
    }];
    
}
-(void)button:(UIButton *)button
{
    
    self.searchController.searchBar.text = button.titleLabel.text;
    if (_searchController.searchBar.text.length != 0) {
        [_viewshow removeFromSuperview];
        _tableview.scrollEnabled = YES;
        
    }
    _searchController.active =YES;
    
}
//设置区域的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    if (self.searchController.active) {
//        return [self.searchList count];
//    }else{
//        // return [self.dataList count];
//        return 0;
//    }
    return _searchList.count>0?_searchList.count:0;
}
//返回单元格内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *flag=@"cellFlag";
    DDSoundTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:flag];
    if (cell==nil) {
        cell=[[DDSoundTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:flag];
    }
    if (_searchList.count != 0) {
        DDSoundModel *model = _searchList[indexPath.row];
        
        cell.model = model;
    }
    return cell;
}
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    if (_searchController.searchBar.text.length != 0) {
        [self hubShow];
        [self setUpData];
         [self hubHide];
    }
    NSString *searchString = [self.searchController.searchBar text];
    
    if (searchString.length == 0) {
    
        [self.view addSubview:_viewshow];
        self.tableview.scrollEnabled = NO;
    }else
    {
        [_viewshow removeFromSuperview];
        self.tableview.scrollEnabled = YES;
        
    }
//    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
//    if (self.searchList!= nil) {
//       [self.searchList removeAllObjects];
//    }
//    //过滤数据
//    self.searchList= [NSMutableArray arrayWithArray:[_dataList filteredArrayUsingPredicate:preicate]];
    //刷新表格
    [self.tableview reloadData];
}
- (void)leftButton:(UIButton *)button
{
    _searchController.active = NO;
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _searchController.active = NO;
    DDSoundModel *model = self.searchList[indexPath.row];
    DDSoundDetailsViewController *sdVC = [[DDSoundDetailsViewController alloc]init];
    sdVC.html5 = model.html5;
    sdVC.pageid = model.pageid;
    sdVC.category = model.category;
    sdVC.author = model.author;
    sdVC.titlename = model.title;
    sdVC.thumbnail = model.thumbnail;
    [self.navigationController pushViewController:sdVC animated:YES];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    _searchController.active =NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
